package com.xin.data.simbapesa.base;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseBindingAdapter1<T, VB extends ViewBinding>
        extends RecyclerView.Adapter<BaseBindingAdapter1.BindingViewHolder<VB>> {

    protected final List<T> dataList;

    protected BtnItemClickListener onBtnItemClickListener;

    public BaseBindingAdapter1(List<T> dataList) {
        this.dataList = dataList != null ? dataList : new ArrayList<>();
    }

    @Override
    public int getItemViewType(int position) {
        return getItemType(dataList.get(position));
    }

    @NonNull
    @Override
    public BindingViewHolder<VB> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        VB binding = createBinding(inflater, parent, viewType);
        return new BindingViewHolder<>(binding);
    }


    @Override
    public void onBindViewHolder(@NonNull BindingViewHolder<VB> holder, int position) {
        T item = dataList.get(position);
        bindData(holder.binding, item, position);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void updateData(List<T> newData) {
        dataList.clear();
        dataList.addAll(newData);
        notifyDataSetChanged();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void updateAllData() {
        notifyDataSetChanged();
    }


    protected abstract void bindData(VB binding, T item, int position);

    protected abstract int getItemType(T item);

    protected abstract VB createBinding(LayoutInflater inflater, ViewGroup parent, int viewType);

    public static class BindingViewHolder<VB extends ViewBinding>
            extends RecyclerView.ViewHolder {
        public final VB binding;

        public BindingViewHolder(VB binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }

    public void setOnBtnItemClickListener(BtnItemClickListener onBtnItemClickListener) {
        this.onBtnItemClickListener = onBtnItemClickListener;
    }

    public interface BtnItemClickListener {
        void onItemClick(int position);
    }
}